/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-11-15
 * Time: 22:05
 */
class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
public class Solution {
    public int index;//记录反序列化时对应的字符串的下标
    public StringBuilder stringBuilder=new StringBuilder();//拼接字符串

    //通过后序遍历序列化
    //注意要添加分隔标志,以便还原
    public void postOrder(TreeNode root){
        if(root==null){
            stringBuilder.append("#;");
            return ;
        }
        postOrder(root.left);
        postOrder(root.right);
        stringBuilder.append(root.val+";");
    }

    //树的序列化
    String Serialize(TreeNode root) {
        postOrder(root);
        return stringBuilder.toString();
    }


    //利用后序来还原树
    public TreeNode postCreateTree(String[] arr){
        if(index<0){
            return null;
        }
        String str=arr[index];
        index--;//注意只要下标合法都要及时的减一
        if(str.equals("#")){
            //为空节点
            return null;
        }
        int val=Integer.parseInt(str);
        TreeNode root=new TreeNode(val);
        //后序遍历先创建右子树
        root.right=postCreateTree(arr);
        root.left=postCreateTree(arr);
        return root;
    }

    //反序列化
    TreeNode Deserialize(String str) {
        String [] arr=str.split(";");//先按照分隔符分隔
        int length=arr.length;
        this.index=length-1;
        return postCreateTree(arr);
    }
}
